package com.shchekoldin.juliet.json.codec.encoder;

class StringUtil {

    /**
	 * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F).
	 * @param value
	 * @return
	 */
    public static String escape(String value) {
        if ( value == null ) return null;

        StringBuffer buffer = new StringBuffer();
        escape(value, buffer);

        return buffer.toString();
    }

    /**
     * @param value - Must not be null.
     * @param buffer
     */
    private static void escape(String value, StringBuffer buffer) {
        buffer.append("\"");

        for (int i = 0; i < value.length(); ++i) {
            char ch = value.charAt(i);

            switch (ch) {
                case '"':
                    buffer.append("\\\"");
                    break;
                case '\\':
                    buffer.append("\\\\");
                    break;
                case '\b':
                    buffer.append("\\b");
                    break;
                case '\f':
                    buffer.append("\\f");
                    break;
                case '\n':
                    buffer.append("\\n");
                    break;
                case '\r':
                    buffer.append("\\r");
                    break;
                case '\t':
                    buffer.append("\\t");
                    break;
                case '/':
                    buffer.append("\\/");
                    break;
                default:
                    // Reference: http://www.unicode.org/versions/Unicode5.1.0/
                    if ( (ch >= '\u0000' && ch <= '\u001F')
                        || (ch >= '\u007F' && ch <= '\u009F')
                        || (ch >= '\u2000' && ch <= '\u20FF') ) {
                        String charUnicodeValue = Integer.toHexString(ch);
                        buffer.append("\\u");

                        for (int k = 0; k < 4 - charUnicodeValue.length(); k++) {
                            buffer.append('0');
                        }

                        buffer.append(charUnicodeValue.toUpperCase());
                    } else {
                        buffer.append(ch);
                    }
            }
        }

        buffer.append("\"");
	}

    public static void removeLastChar(StringBuffer stringBuffer) {
        int size = stringBuffer.length();
        if ( size == 0 ) return;
        stringBuffer.delete(size - 1, size);
    }

    public static String capitalize(String value) {
        return value.substring(0, 1).toUpperCase() + value.substring(1);
    }

    public static String decapitalize(String value) {
        return value.substring(0, 1).toLowerCase() + value.substring(1);
    }

}
